package com.chinameyer.equipment_ebook.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chinameyer.equipment_ebook.bean.Event;
import com.chinameyer.equipment_ebook.bean.User;
import com.chinameyer.equipment_ebook.bo.MyDefineBO;
import com.chinameyer.equipment_ebook.mapper.EventMapper;
import com.chinameyer.equipment_ebook.mapper.UserMapper;
import com.chinameyer.equipment_ebook.util.MD5Utils;
import com.chinameyer.equipment_ebook.util.QRCodeUtils;
import com.chinameyer.equipment_ebook.util.ZipUtil;
import com.chinameyer.equipment_ebook.vo.LoginVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;


/**
 * @Author meyer@HongYe
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MD5Utils md5Utils;
    @Autowired
    private EventMapper eventMapper;
    @Autowired
    private MyDefineBO myDefineBO;
    @Autowired
    private ZipUtil zipUtil;


    public boolean checkUsername(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getUsername,username);
        return this.userMapper.selectCount(wrapper) > 0;
    }

    public LoginVO verifyAccount(String username, String password) {
        String encodedPassword = md5Utils.stringToMD5(password);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getUsername,username).eq(User::getPassword,encodedPassword);
        User user =  this.userMapper.selectOne(wrapper);
        LoginVO loginVO = new LoginVO();
        if(StringUtils.isEmpty(user)){
            return null;
        }
        BeanUtils.copyProperties(user,loginVO);
        return loginVO;
    }

    public boolean updatePassword(LoginVO loginVO, String newPassword) {
        String encodedPassword = md5Utils.stringToMD5(newPassword);
        User oldUser = this.userMapper.selectById(loginVO.getId());
        oldUser.setPassword(encodedPassword);
        return this.userMapper.updateById(oldUser) > 0;
    }

    public String downloadQRCode(String equipmentNo) throws Exception {
        QueryWrapper<Event> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Event::getEquipmentNo,equipmentNo);
        List<Event> eventList = this.eventMapper.selectList(wrapper);
        String path = "";
        for (Event event:eventList) {
            if(!StringUtils.isEmpty(event.getUrl())){
                String manualType = this.eventMapper.selectTypeById(event.getId());
                String imgPath = new File(this.getClass().getResource("/").getPath()) + "/static/upload/qrLogo.png"; //嵌入二维码的图片绝对路径也可以不放
                String basePath = new File(this.getClass().getResource("/").getPath()) + "/static/qrcode/"+ equipmentNo + "/";
                File fileTemp = new File(basePath);
                if (!fileTemp.exists()){
                    fileTemp.mkdirs();
                }
                String destPath = new File(this.getClass().getResource("/").getPath()) + "/static/qrcode/"+ equipmentNo + "/" +manualType+".png";
                String url = myDefineBO.getDomain1() + "/pdfjs/web/viewer.html?file=/v1/user/getManual/" +event.getId()+"/";
                QRCodeUtils.encode(url, imgPath, destPath, true);

                path = new File(this.getClass().getResource("/").getPath()) + "/static/qrcode/"+ equipmentNo;
            }
        }
        return zipUtil.fileToZip(path,equipmentNo);
    }

    public void getManual(Integer eventId, HttpServletResponse response) {
        String pdfUrl = this.eventMapper.selectById(eventId).getUrl();
        int lastIndex = pdfUrl.lastIndexOf("/");
        String pdfName = pdfUrl.substring(lastIndex+1);
        String basePath = myDefineBO.getPdfPath();
        String pdfLoc = basePath + pdfName;
        File file = new File(pdfLoc);
        if (file.exists()) {
            byte[] data = null;
            FileInputStream input=null;
            try {
                input= new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);
                response.getOutputStream().write(data);
            } catch (Exception e) {
                System.out.println("pdf文件处理异常：" + e);
            }finally{
                try {
                    if(input!=null){
                        input.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
